package com.unina.is2.astafantaunina.service;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;

import com.unina.is2.astafantaunina.activity.LegheActivity;
import com.unina.is2.astafantaunina.chat.ChatGruppo;
import com.unina.is2.astafantaunina.chat.PresenceListener;
import com.unina.is2.astafantaunina.chat.ReceivePacket;
import com.unina.is2.astafantaunina.chat.ReceivePacketChat;
import com.unina.is2.astafantaunina.chat.XMPP;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class ServiceOpenfire extends IntentService{

	private final static String MY_PREFERENCES = "UtenteAstaFantaunina";
	private String username, password, lega_scelta;
	private static XMPPConnection connection = null;
	//private MultiUserChat mu;
	
	public ServiceOpenfire() {
		
		super("Servizio avviato");
		// TODO Auto-generated constructor stub
	}

	 /**
	   * The IntentService calls this method from the default worker thread with
	   * the intent that started the service. When this method returns, IntentService
	   * stops the service, as appropriate.
	   */
	/*
	@Override
	public void onCreate(){
		
	}
	*/
	
	@Override
	protected void onHandleIntent(Intent intent) {	
		
		Log.w("servizio", "servizio avviato");
		
		SharedPreferences s = getSharedPreferences(MY_PREFERENCES,Context.MODE_PRIVATE);
		username = s.getString("username", "nessun username");
		password = s.getString("password", "nessuna password");
		lega_scelta = s.getString("lega_scelta", "nessuna lega");
		
		XMPP xmpp = null;
		
		//Ci colleghiamo al server openfire
		if(connection==null){
			xmpp = XMPP.getSingletonXMPP(username, password);
			connection = xmpp.connectToServer();
			
			/*
	 		 * listeners dei messaggi xmpp trasmessi dal server
	 		 */
		    PacketTypeFilter presenceFilter=new PacketTypeFilter(Presence.class);
			ReceivePacket listener = ReceivePacket.getListener();
			ReceivePacketChat listenerChat = ReceivePacketChat.getListener();
			PresenceListener presence = PresenceListener.getListener();
			connection.addPacketListener(listenerChat, new MessageTypeFilter(Message.Type.chat));
			connection.addPacketListener(listener, new MessageTypeFilter(Message.Type.groupchat));
			connection.addPacketListener(presence, presenceFilter);
		}
		
		ChatGruppo chat = ChatGruppo.getSingletonChatGruppo(connection, lega_scelta, username);
		
		//mu = chat.joinStanza();
		chat.joinStanza();
		
		Intent i = new Intent("ABILITA_BUTTON");

		LegheActivity.getContext().sendBroadcast(i);
		
		
 		}
	
	
		public static void azzeraConnessione(){
			connection = null;
		}

}
